var sysType = ''

/*tab切换*/
function tab(oa, ob, oc, od) {
    var index = od || 0;
    var oo = oc ? oc : "on";
    if (od != undefined) {
        $(oa).eq(index).addClass(oo).siblings().removeClass(oo);
        $(ob).eq(index).addClass(oo).siblings().removeClass(oo);
    }
    $(oa).click(function (event) {
        var index = $(this).index();
        $(oa).removeClass(oo);
        $(oa).eq(index).addClass(oo);
        $(ob).removeClass(oo);
        $(ob).eq(index).addClass(oo)
    });
    $(oa).eq(0).trigger('click');
}
//getID
function getID(length = 7) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}
/* toast 结束 */
/*判断浏览器*/
var browser = {
    versions: function () {
        var u = navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
            qq: u.match(/\sQQ/i) == " qq" //是否QQ

        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}
//是安卓
if (browser.versions.android) {
    $("body").addClass("android");
    sysType = 'android'
};
//是IOS
if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
    $("body").addClass("ios");
    sysType = 'ios'
};
/* toast 开始 */
var toast = function (param = {}) {
    let text = param.message || ''
    let type = param.type || 'text'
    let icon = param.icon || ''
    let loadingType = param.loadingType || 'circular'
    let forbidClick = param.forbidClick || false
    let position = param.position || 'middle'
    let duration = param.duration == 0 ? 0 : 1500;
    let transition = param.transition || 'van-fade'
    let getContainer = param.getContainer || 'body'
    if (typeof param === "object") {
        type = param.type || 'loading'
    }

    if (typeof param === "string") {
        text = param
    }

    let id = getID()
    let pic = ``
    if (type == 'loading' && !param.icon) {
        if (loadingType == 'circular') {
            pic = `<div class="van-loading van-loading--circular van-toast__loading"><span class="van-loading__spinner van-loading__spinner--circular"><svg viewBox="25 25 50 50" class="van-loading__circular"><circle cx="50" cy="50" r="20" fill="none"></circle></svg></span></div>`
        } else {
            pic = `<div class="van-loading van-loading--spinner van-toast__loading"><span class="van-loading__spinner van-loading__spinner--spinner"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></span></div>`
        }
    } else if (type == 'success') {
        pic = `<i class="iconfont iconsuccess van-toast__icon"></i>`
    } else if (type == 'fail') {
        pic = '<i class="iconfont iconfail van-toast__icon"></i>'
    } else {
        if (icon != '') {
            if (icon.indexOf("http") != -1 || icon.indexOf("https") != -1) {
                pic = `<i class="iconfont van-toast__icon"><img src="${icon}" class="van-icon__image"></i>`
            } else {
                pic = `<i class="iconfont ${icon} van-toast__icon"></i>`
            }
            type = 'none'
        }
    }

    let dom = `<div class="van-toast van-toast--${position} van-toast--${type} ${transition}-enter-active" style="z-index: 2002;" id='${id}' data-transition='${transition}'>${pic}<div class="van-toast__text">${text}</div></div>`;

    $('.van-toast').remove()
    $(getContainer).append(dom)
    if (forbidClick) {
        $('body').addClass('van-toast--unclickable')
    }
    if (duration > 0) {
        setTimeout(() => {
            toast.clean($('#' + id))
        }, duration);
    }

    return $('#' + id)
}
toast.clean = function (dom = null) {
    if (dom == null) {
        dom = $('.van-toast')
    }
    let transition = dom.data("transition") || 'van-fade'
    dom.addClass(`${transition}-leave-active`)
    $('body').removeClass('van-toast--unclickable')
    setTimeout(() => {
        dom.remove()
    }, 800);
}
toast.loading = function (param) {
    if (typeof param == 'undefined') {
        param = {
            message: '加载中...',
            forbidClick: true,
        }
    }
    param.type = 'loading';
    toast(param)
}
toast.ajaxLoading = function (str) {
    param = {
        message: str,
        duration: 0,
        forbidClick: true,
        type: 'loading'
    }
    toast(param)
}

toast.success = (text) => {
    let param = {}
    param.message = text || '成功'
    param.type = 'success'
    toast(param)
}

toast.fail = (text) => {
    let param = {}
    param.message = text || '失败'
    param.type = 'fail'
    toast(param)
}
/*显示*/
function showAnimation(oa, ob) {
    ob ? ob = ob : ob = 300;
    //遮罩层不存在 写入一个
    if ($(".pop").length == 0) {
        $("body").append('<div class="pop"></div>');
    };
    $(oa).addClass('active show');//显示遮罩
    //删除动画
    setTimeout(function () {
        $(oa).removeClass('show');
    }, ob);
    // $(".pop").one('click', function () {
    //     hideAnimation(oa, ob)
    // })
}
/*隐藏*/
function hideAnimation(oa, ob, del = false) {
    ob ? ob = ob : ob = 300;
    $(oa).addClass('hide');//显示遮罩
    //删除动画
    setTimeout(function () {
        $(oa).removeClass('active hide');
        if (del) { $(oa).remove(); }
    }, ob);
}
/*大图预览*/
function previewSwiper() {
    var swiperHtml = `<div class="swiper-container swiper-box">
                        <a href="javascript:;" class="swiper-box-close iconfont iconclose2"></a>
                        <div class="swiper-wrapper"></div>
                        <div class="swiper-pagination swiper-pagination-white"></div>
                    </div>`;
    $("body").append(swiperHtml);//写入
    var myImg = $(".swiper-box");//切换层
    /*图片切换*/
    var mySwiper = new Swiper('.swiper-box', {
        resistanceRatio: 0,//边缘抵抗率
        spaceBetween: 10,//间距
        pagination: {
            el: '.swiper-box .swiper-pagination',
            clickable: true,
        },
    });

    /*打开大图预览*/
    $(document).on('click', '.openimg img', function (event) {
        var imgList = $(this).parents(".openimg").find("img");
        var index = 0;
        var html = "";
        for (var i = 0; i < imgList.length; i++) {
            if ($(imgList[i]).attr('src') == $(this).attr('src')) {
                index = i;
            }
            html += '<div class="swiper-slide"><img class="img100" src="' + $(imgList[i]).attr('src') + '"></div>';
        };
        myImg.find('.swiper-wrapper').html(html);
        mySwiper.updateSlides();//更新
        mySwiper.slideTo(index, 10, false);//切换到第一个slide，速度为1秒
        myImg.addClass("on");
    });
    /*关闭大图预览*/
    $(".swiper-box-close").click(function (event) {
        myImg.removeClass("on");
    });
}
//底部加载效果
var downText = {
    domClass: 'dropload-down',
    domRefresh: '<div class="dropload-refresh">↑上拉加载更多</div>',
    domLoad: '<div class="dropload-load"><span class="loading"></span>加载中...</div>',
    domNoData: '<div class="dropload-noData">暂无数据</div>',
    domAllData: '<div class="dropload-noData">已全部加载</div>'
}
//首页滑到到底部加载数据
function downFun(el, back) {
    var isScroll = (el.attr("isscroll") == "true") ? true : false;//是否可加载
    var loadzt = el.find(".dropload-down");//加载状态
    //
    if (!isScroll) {
        el.attr('isscroll', 'false');
    }
    //是否有加载状态
    if (loadzt.length == 0) {
        el.append('<div class="' + downText.domClass + '">' + downText.domLoad + '</div>');
    };
    //绑定滚动事件
    el.scroll(function () {
        var tt = $(this);
        isScroll = (tt.attr("isscroll") == "true") ? true : false;//是否可加载
        loadzt = tt.find(".dropload-down");//加载状态
        //加载中
        if (!isScroll) {
            return false;
        };
        //滑到底部
        if (tt[0].scrollTop + tt[0].clientHeight >= tt[0].scrollHeight - 60 && isScroll && tt[0].scrollTop > 100) {
            tt.attr("isscroll", "false");//设置不可加载
            loadzt.html(downText.domLoad);//修改加载状态为加载中
            //进行数据加载
            back ? back() : downFunLoad(tt, tt.find(".dtbox"));
        }
    });
}
//底部加载有数据
function downFunYes(oa) {
    oa.attr("isscroll", "true");//设置可加载
    oa.find(".dropload-down").html(downText.domRefresh);//修改加载状态为加载中
}
//底部加载没有数据
function downFunNo(oa) {
    oa.attr("isscroll", "false");//设置不可加载
    oa.find(".dropload-down").html(downText.domNoData);//修改加载状态为没有数据
}
//底部加载没有数据 图片模式
function downFunNoImg(oa, imgHtml) {
    imgHtml = imgHtml ? imgHtml : '<div class="dsearchno" style="display:block;"><div class="dseimg"><img class="img" src="/ziyuan/fhweb/images/dblank.png" alt=""></div><p>暂无相关信息</p></div>';
    oa.attr("isscroll", "false");//设置不可加载
    oa.find('.dtbox').html(imgHtml);
    oa.find(".dropload-down").remove();//修改加载状态为没有数据
}
//底部数据全部加载
function downFunAll(oa) {
    oa.attr("isscroll", "false");//设置不可加载
    oa.find(".dropload-down").html(downText.domAllData);//修改加载状态为全部加载
}
//加载中
function downFunLoading(oa) {
    oa.attr("isscroll", "false");//设置不可加载
    oa.find(".dropload-down").html(downText.domLoad);//修改加载状态为全部加载
}
//获取地址栏参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    return r ? decodeURIComponent(r[2]) : null;
}
/*返回顶部*/
//点击返回顶部，滚动到指定高度显示/隐藏按钮，显示与隐藏效果是css3
function scrollGoTop(elem, scrollH, type) {
    //elem：绑定元素
    //scrollH：指定高度
    //type：1 - content滚动  2 - window滚动
    var elem = $(elem);
    let scrollBoxA = type == 1 ? $('.content') : $(window);
    let scrollBoxB = type == 1 ? $('.content') : $("html, body");
    //按钮隐藏与显示
    scrollBoxA.scroll(function () {
        if ($(this).scrollTop() > scrollH) {
            elem.addClass('on');
        } else {
            elem.removeClass('on');
        };
    });
    //返回顶部
    elem.click(function () {
        scrollBoxB.animate({ scrollTop: 0 }, 600);
    });
}

//显示返回顶部
function showGoTop(type = 1) {
    let html = '<div class="sys-gotop"><img class="img100" src="images/common/gotop.png" alt=""></div>';
    $("body").append(html);
    let box = type == 1 ? $('.content') : $(window);
    // 返回顶部
    scrollGoTop('.sys-gotop', 200, type);
}
$(function () {
    //返回顶部
    // $('.content').append(`<div class="gotop"><img class="imgcover" src="/static_h5/images/top.png" alt=""></div>`);
    //返回顶部
    scrollGoTop('.gotop', 100, 1);
    //写入APP提示弹窗
    addAppPop()
});


//写入APP提示弹窗
function addAppPop() {
    let html = '';
    //判断系统 ios
    if (sysType == 'ios') {
        html = `<a class="pop-down-btn" href="https://h5.ios.sssgo.com/#/" target="_blank">打开</a>`
    }
    //判断系统 android
    if (sysType == 'android') {
        html = `<div class="pop-down-btn pop-down-android">下载APP</div>`
    }
    //写入
    $("body").append(`<div class="pop"></div>
                    <div class="tier-pop tier-center pop-down">
                        <div class="pop-down-main">
                            <img class="img100" src="/themes/simplebootx/Public/mobile/images/common/app.png" alt="">
                            ${html}
                        </div>
                        <div class="pop-down-close iconfont iconguanbi"></div>
                    </div>`)

}
//显示APP提示弹窗
$(document).on('click', '.show-app', function () {
    if ($(".pop-down").length > 0) {
        showAnimation('.tier-pop,.pop');
    } else {
        addAppPop()
        showAnimation('.tier-pop,.pop');
    }
})
//关闭APP提示弹窗
$(document).on('click', '.pop-down-close', function () {
    hideAnimation('.tier-pop,.pop');
})
/* 支付弹窗 0*/
//关闭支付提示弹窗
$(document).on('click', '.pay-bpop-close', function () {
    hideAnimation('.pay-bpop,.pop');
})
/* 支付弹窗 1*/


//写入折扣弹窗
function addZkPop() {
    let userinfo = window.localStorage.getItem('userinfo');
    //已登录
    if (userinfo) {
        //写入
        $("body").append(`<div class="tier-pop jszk-box">
            <div class="jszk-close"></div>
            <div class="jszk-title flex-center-align"><span>解锁折扣</span></div>
            <div class="jszk-img">
                <img class="img100" src="/themes/simplebootx/Public/mobile/images/common/jszk.png" />
            </div>
            <div class="jszk-tp">
                <span>严控游戏</span>
            </div>
            <div class="jszk-p flex-column flex-center-align">
                <span>可先玩其他游戏进行等级提升后解锁</span>
                <span>联系客服申请解锁</span>
            </div>
            <div class="jszk-b flex-center-align mt30" onclick="goKefu()">
                <span>联系客服</span>
            </div>
        </div>`)
    }
    else {
        //未登录写入
        $("body").append(`<div class="tier-pop jszk-box">
            <div class="jszk-close"></div>
            <div class="jszk-title flex-center-align"><span>请登录账号</span></div>
            <div class="jszk-img2">
                <img class="img100" src="/themes/simplebootx/Public/mobile/images/common/zkdl.png" />
            </div>
            <div class="jszk-p mt30">
                <span>登录账户后：可查看福利币折扣</span>
            </div>
            <div class="jszk-b flex-center-align mt30" onclick="goLogin()">
                <span>立即登录</span>
            </div>
        </div>`)
    }
}
//显示折扣弹窗
$(document).on('click', '.show-zk', function (e) {
    e.stopPropagation();
    e.preventDefault();
    if ($(".jszk-box").length > 0) {
        showAnimation('.jszk-box,.pop');
    } else {
        addZkPop()
        showAnimation('.jszk-box,.pop');
    }
})
//关闭折扣弹窗
$(document).on('click', '.jszk-close', function () {
    hideAnimation('.jszk-box,.pop');
})
//下载APP
$(document).on('click', '.pop-down-android', function () {
    window.open('https://houduan.sssgo.com/box/?ag=cps001&gid=1#/');
    // download('https://sssgo.oss-cn-shanghai.aliyuncs.com/games/android/baidutg/yxhz_baidutg_121.apk');
})

/* 统计 */
function statistics(event) {
    // let id = window.location.href.split('/').pop().split('.')[0];//id
    // let params = {
    //     event: event,//article_view=文章访问 game_download=游戏下载 collection_view=集合访问 rank_view=排行榜访问
    //     id: id,
    //     source: '2',
    // }
    // $.ajax({
    //     url: 'https://www.yangtuoyou.com/web/burying/point',
    //     type: 'post',
    //     contentType: 'application/json',
    //     data: JSON.stringify(params),
    //     dataType: 'json'
    // })
}
//下载
function download(url) {
    const a = document.createElement('a');
    a.href = url;
    a.target = '_blank';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
/* 下载APK */
$(document).on('click', '.down-btn', function () {
    let url = $(this).attr('down-url');
    download(url);
})
/* 下载盒子 */
$(document).on('click', '.down-btn-hz', function () {
    download("https://download.yangtuoyou.com/apk/package/android/m/yangtuoyou.apk");
})

//分页状态
function pageState(list, data, limit = 10) {
    //list：列表所有数据条数
    //limit：每页多少条
    //data：本次请求返回多少条数据
    let status;
    if (list == 0) {
        status = 'noData';
    } else if (list % limit > 0 || (list % limit == 0 && data == 0)) {
        status = 'noMore';
    } else {
        status = 'more';
    }
    return status;
}

//精度浮点乘法
function accMultiply(arg1, arg2) {
    let m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split('.')[1].length;
    } catch (e) {
        // console.log(e)
    }
    try {
        m += s2.split('.')[1].length;
    } catch (e) {
        // console.log(e)
    }
    return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m);
}
/*加法函数，用来得到精确的加法结果*/
function accAdd(arg1, arg2) {
    let r1, r2, m, c;
    try {
        r1 = arg1.toString().split('.')[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split('.')[1].length;
    } catch (e) {
        r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
        let cm = Math.pow(10, c);
        if (r1 > r2) {
            arg1 = Number(arg1.toString().replace('.', ''));
            arg2 = Number(arg2.toString().replace('.', '')) * cm;
        } else {
            arg1 = Number(arg1.toString().replace('.', '')) * cm;
            arg2 = Number(arg2.toString().replace('.', ''));
        }
    } else {
        arg1 = Number(arg1.toString().replace('.', ''));
        arg2 = Number(arg2.toString().replace('.', ''));
    }
    return (arg1 + arg2) / m;
}
/*减法函数，用来得到精确的减法结果*/
function accSub(arg1, arg2) {
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split('.')[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split('.')[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//去客服页面
$(document).on('click', '.open-kefu', function () {
    window.open('https://work.weixin.qq.com/kfid/kfcb20ec0d83dee9a10', '_blank');
})
//去首页
function goIndex() {
    window.location.href = window.location.origin + '/mobile/'; //首页
}
function islogin() {
    return localStorage.getItem('userinfo') ? true : false;
}
//去指定页面并验证登录
function isloginGoHref(url) {
    if (islogin()) {
        window.location.href = url;
    } else {
        goLogin()
    }
}
//去登录
function goLogin() {
    hideAnimation('.jszk-box,.pop');
    window.location.href = window.location.origin + '/Mobile/user/login.html';
}
//去客服页面
function goKefu() {
    hideAnimation('.jszk-box,.pop');
    window.location.href = window.location.origin + '/Mobile/user/kf_index.html';
}
function downTime(end_time) {
    //请传字符串或者数字
    //处理位数
    end_time += '';
    if (end_time.length < 13) {
        end_time = parseInt(end_time + '000')
    }
    //计算
    let seconds = (new Date(end_time).getTime() - new Date().getTime()) / 1000;
    let day = Math.floor(seconds / (60 * 60 * 24)); //天
    let hour = Math.floor(seconds / (60 * 60)) - day * 24; //小时
    let minute = Math.floor(seconds / 60) - hour * 60 - day * 24 * 60; //分钟
    let remainingTime = '';
    //天
    if (day) {
        remainingTime += day + '天';
    }
    //小时
    if (hour) {
        hour = (day && hour < 10) ? '0' + hour : hour;
        remainingTime += hour + '小时';
    }
    //分钟
    if (minute) {
        minute = (hour && minute < 10) ? '0' + minute : minute;
        remainingTime += minute + '分钟';
    }
    return remainingTime
}

//传时间戳 返回数组形式的日期
function getMyDate(str) {
    str += ''
    str = str.length < 11 ? parseInt(str) * 1000 : parseInt(str);
    var oDate = new Date(str),
        Year = oDate.getFullYear(),
        Month = oDate.getMonth() + 1,
        Day = oDate.getDate(),
        Hour = oDate.getHours(),
        Min = oDate.getMinutes(),
        Sen = oDate.getSeconds(),
        week = oDate.getDay();
    return [Year, addZero(Month), addZero(Day), addZero(Hour), addZero(Min), addZero(Sen), week];

    function addZero(num) {
        if (parseInt(num) < 10) {
            num = '0' + num;
        }
        return num;
    }
}
//格式化日期
function formatTimeFun(time, type = 1) {
    let arr = getMyDate(time);
    let str = '';
    switch (type) {
        case 1:
            str = arr[0] + '-' + arr[1] + '-' + arr[2];
            break;
        case 2:
            str = arr[0] + '-' + arr[1] + '-' + arr[2] + ' ' + arr[3] + ':' + arr[4] + ':' + arr[5];
            break;
    }
    return str;
}
//去支付
function goPay(data, type) {
    //微信
    if (type == 'wx') {
        window.location.href = data
    }
    //支付宝
    if (type == 'zfb') {
        if (document.forms[0]) document.forms[0].remove();
        let div = document.createElement('div')
        div.id = 'alipay';
        div.innerHTML = data
        document.body.appendChild(div)
        document.forms[0].submit()
    }
}
//刷新页面
function refreshFun(time = 0) {
    setTimeout(() => {
        window.location.reload()
    }, time);
}



/*支付确认弹窗0*/
//写入支付确认弹窗
function addPayPop(id) {
    //写入
    $("body").append(`<div class="pop"></div>
		<div class="tier-pop pay-confirm">
			<div class="pay-title">是否已支付？</div>
			<div class="pay-cbtn flex-between">
				<div class="pay-cbtn-a flex-center-align">未支付</div>
				<div class="pay-cbtn-b flex-center-align" id="${id}">已支付</div>
			</div>
		</div>`)
}
//显示支付确认弹窗
function showPayPop() {
    if ($(".pay-confirm").length > 0) {
        showAnimation('.pay-confirm,.pop');
    } else {
        addPayPop()
        showAnimation('.pay-confirm,.pop');
    }
}
//写入支付成功弹窗
function addPaySuccPop() {
    //写入
    $("body").append(`<div class="tier-pop pay-succ">
			<div class="pay-img">
				<img class="img100" src="./images/suuc.png" alt="">
			</div>
			<div class="pay-text">支付成功</div>
			<div class="pay-btn flex-center-align">返回首页</div>
		</div>`)
}
//显示支付成功弹窗
function showPaySuccPop() {
    if ($(".pay-succ").length == 0) {
        addPaySuccPop()
    }
    hideAnimation('.pay-confirm');
    $(".pay-succ").show();
}
//关闭支付确认弹窗
$(document).on('click', '.pay-cbtn-a', function () {
    hideAnimation('.pay-confirm,.pop');
})
//去确认是否支付完成
$(document).on('click', '.pay-cbtn-b', function () {
    showPaySuccPop()

    // let id = $(this).attr('id');
    // toast.ajaxLoading('确认中...')
    // let params = {
    //     id: id
    // }
    // $api.djqPay(params).then(res => {
    //     if (res.code == 1) {
    //         toast.clean();
    //         addPaySuccPop()
    //     } else {
    //         toast.success(res.msg)
    //     }
    // })
})
//支付成功确认按钮
$(document).on('click', '.pay-btn', function () {
    // goIndex();
    hideAnimation('.pay-succ,.pop');
    $(".pay-succ").hide();
})
/*支付确认弹窗1*/